/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.healthecology.operator;

import com.huawei.healthecology.data.platform.PlatformCallback;
import com.huawei.healthecology.data.utils.OptionalX;
import com.huawei.healthecology.log.LogUtil;

import lombok.Builder;
import ohos.agp.components.webengine.WebView;

import java.util.Optional;

/**
 * The remote operator for H5/Web view
 */
@Builder
public class H5RemoteOperator implements PlatformCallback {
    private static final String TAG = "H5RemoteOperator";

    private static final String JAVA_SCRIPT_HEADER = "javascript";

    private final WebView webViewInstance;

    private final String remoteJsMethod;

    @Override
    public void onResponse(String response) {
        OptionalX.ofNullable(webViewInstance)
            .ifPresent(webView -> Optional.ofNullable(webView.getContext())
                .ifPresent(context -> context
                    .getUITaskDispatcher()
                    .asyncDispatch(() -> webView.executeJs(
                        buildResponse(response),
                        message -> LogUtil.debug(TAG, message)))))
            .ifNotPresent(() -> LogUtil.debug(TAG, buildResponse(response)));
    }

    private String buildResponse(String response) {
        return String.format("%s:%s('%s')",
            JAVA_SCRIPT_HEADER, remoteJsMethod, response);
    }
}
